package com.example.project_01.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.project_01.commons.ApiResponse;
import com.example.project_01.dto.account.AccountDTO;
import com.example.project_01.dto.account.LoginResponseDTO;
import com.example.project_01.mapper.AccountMapper;
import com.example.project_01.pojo.Account;
import com.example.project_01.service.AccountService;
import com.example.project_01.utils.MD5Password;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * ClassName: AccountServiceImpl
 * Package: com.example.project_01.service.impl
 * Description:
 *
 * @Author ShiYi
 * @Create 2025/10/13 11:38
 * @Version 1.0
 */
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    AccountMapper accountMapper;

    /**
     * 用户登录
     *
     * @param accountDTO 传入的用户信息（Account类型）
     * @return
     */
    @Override
    public ApiResponse<LoginResponseDTO> loginService(AccountDTO accountDTO) {
        if (accountDTO == null) {
            return ApiResponse.clientError(400, "");
        }

        if (accountDTO.getUname() == null || StrUtil.isBlank(accountDTO.getUname())) {
            return ApiResponse.clientError(400, "用户名不能为空");
        }
        if (accountDTO.getPwd() == null || StrUtil.isBlank(accountDTO.getPwd())) {
            return ApiResponse.clientError(400, "密码不能为空");
        }

        // 根据用户名查询用户信息
        QueryWrapper<Account> wrapper = new QueryWrapper<>();
        wrapper.eq("uname", accountDTO.getUname());
        // 数据库返回的用户信息
        Account account = accountMapper.selectOne(wrapper);
        if (account == null) {
            return ApiResponse.clientError(400, "登录失败，请检查用户名和密码");
        }

        // 密码加密(登录时输入的密码 + 数据库存储的盐值)
        String encryptedPassword = MD5Password.md5Password(accountDTO.getPwd(), account.getSalt());

        // 用户存在，验证用户名和密码
        if (accountDTO.getUname().equals(account.getUname()) && encryptedPassword.equals(account.getPwd())) {

            // 转换数据响应给前端（去除敏感字段及非必要字段）
            LoginResponseDTO loginResponseDTO = new LoginResponseDTO();
            loginResponseDTO.setId(account.getId());
            loginResponseDTO.setUname(account.getUname());
            loginResponseDTO.setRealName(account.getRealName());
            loginResponseDTO.setUtype(account.getUtype());

            return ApiResponse.success("登录成功", loginResponseDTO);
        }

        return ApiResponse.clientError(400, "登录失败，请检查用户名和密码");
    }
}
